/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.swapper.reflect.creator;

import com.swapper.reflect.TypeHelper;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * a {@link InstanceCreator<>} static factory.
 */
public final class InstanceCreatorFactory {
  private InstanceCreatorFactory() {
    throw new UnsupportedOperationException(getClass().getSimpleName());
  }

  /**
   * Create a {@link InstanceCreator<T>} instance from the specified type.
   *
   * @param type    the specified type.
   * @param rawType the specified raw type.
   * @param <T>     the specified generic type.
   * @return a {@link InstanceCreator<T>} instance from the specified type.
   */
  public static <T> InstanceCreator<T> create(Type type, Class<? super T> rawType) {
    // Check the validity of arguments
    Objects.requireNonNull(type);
    Objects.requireNonNull(rawType);
    // first try instantiating it with a no-argument constructor.
    InstanceCreator<T> declaredConstructor = fromDeclaredConstructor(rawType);
    if (declaredConstructor != null) {
      return declaredConstructor;
    }
    // next try instantiating it with default implementation.
    InstanceCreator<T> defaultImplementation = fromDefaultImplementation(type, rawType);
    if (defaultImplementation != null) {
      return defaultImplementation;
    }
    // finally, try instantiating it with an unsafe allocator.
    return fromUnsafeAllocator(rawType);
  }

  /**
   * Created {@link InstanceCreator<T>} by a no-argument constructor.
   *
   * @param rawType the specified creator raw type.
   * @param <T>     the specified generic type.
   * @return an instance creator.
   */
  @SuppressWarnings("unchecked")
  private static <T> InstanceCreator<T> fromDeclaredConstructor(Class<? super T> rawType) {
    try {
      final Constructor<? super T> constructor = rawType.getDeclaredConstructor();
      Class<?>[] parameterTypes = constructor.getParameterTypes();
      if (parameterTypes.length == 0) {
        constructor.setAccessible(true);
        return () -> {
          try {
            return (T) constructor.newInstance();
          } catch (Exception e) {
            throw new IllegalStateException("Failed to invoke " + constructor + " with no args.", e);
          }
        };
      }
    } catch (Exception e) {
      // do nothing
    }
    return null;
  }

  /**
   * Created {@link InstanceCreator<T>} by default implementation class.
   *
   * @param type    the specified creator type.
   * @param rawType the specified creator raw type.
   * @param <T>     the specified generic type.
   * @return an instance creator.
   * @see java.util.Collection<>
   * @see java.util.Map<>
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  private static <T> InstanceCreator<T> fromDefaultImplementation(Type type, Class<? super T> rawType) {
    if (Collection.class.isAssignableFrom(rawType)) {
      if (EnumSet.class.isAssignableFrom(rawType)) {
        if (type instanceof ParameterizedType) {
          final Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
          if (elementType instanceof Class) {
            return () -> (T) EnumSet.noneOf((Class) elementType);
          }
        }
        throw new IllegalStateException("Invalid EnumSet type: " + TypeHelper.name(type));
      } else if (SortedSet.class.isAssignableFrom(rawType)) {
        return () -> (T) new TreeSet<>();
      } else if (Set.class.isAssignableFrom(rawType)) {
        return () -> (T) new LinkedHashSet<>();
      } else if (Queue.class.isAssignableFrom(rawType)) {
        return () -> (T) new ArrayDeque<>();
      } else {
        return () -> (T) new ArrayList<>();
      }
    }
    if (Map.class.isAssignableFrom(rawType)) {
      if (EnumMap.class.isAssignableFrom(rawType)) {
        if (type instanceof ParameterizedType) {
          final Type keyType = ((ParameterizedType) type).getActualTypeArguments()[0];
          if (keyType instanceof Class) {
            return () -> (T) new EnumMap((Class) keyType);
          }
        }
        throw new IllegalStateException("Invalid EnumMap type: " + TypeHelper.name(type));
      } else if (ConcurrentNavigableMap.class.isAssignableFrom(rawType)) {
        return () -> (T) new ConcurrentSkipListMap<>();
      } else if (ConcurrentMap.class.isAssignableFrom(rawType)) {
        return () -> (T) new ConcurrentHashMap<>();
      } else if (SortedMap.class.isAssignableFrom(rawType)) {
        return () -> (T) new TreeMap<>();
      } else {
        return () -> (T) new LinkedHashMap<>();
      }
    }
    return null;
  }

  /**
   * Created {@link InstanceCreator<T>} by unsafe allocator.
   *
   * @param rawType the specified creator raw type.
   * @param <T>     the specified generic type.
   * @return an instance creator.
   * @throws UnsupportedOperationException if the specified type is an interface or abstract class.
   * @throws IllegalStateException         if the specified type is not currently supported.
   */
  private static <T> InstanceCreator<T> fromUnsafeAllocator(final Class<? super T> rawType) {
    int modifiers = rawType.getModifiers();
    if (Modifier.isInterface(modifiers)) {
      throw new UnsupportedOperationException("Interface can't be instantiated: " + rawType.getName());
    }
    if (Modifier.isAbstract(modifiers)) {
      throw new UnsupportedOperationException("Abstract class can't be instantiated: " + rawType.getName());
    }
    return () -> {
      try {
        return UnsafeCreator.allocateInstance(rawType);
      } catch (Exception e) {
        throw new IllegalStateException("This type failed to instantiate:" + rawType.getName(), e);
      }
    };
  }
}
